package cn.licoy.wdog.core.controller.hospital2.file;

import cn.licoy.wdog.common.bean.ResponseCode;
import cn.licoy.wdog.common.bean.ResponseResult;
import cn.licoy.wdog.common.exception.RequestException;
import cn.licoy.wdog.core.dto.hospital2.doctor.CertificationDto;
import cn.licoy.wdog.core.dto.hospital2.file.FileUp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Random;

/**
 * @Author Sunne
 * @Date $time$ $date$
 * @Param $param$
 * @return $return$
 **/
@RestController
@RequestMapping(value = "/file")
@Api(tags = {"第二期--文件操作接口"})
public class FileController {
    private static Logger LOGGER = LogManager.getLogger(FileController  .class);

    @PostMapping(value = {"/upload"})
    @ApiOperation(value = "上传文件")
    public ResponseResult<FileUp> upLoadFile(@RequestBody @Validated @RequestParam("file") MultipartFile file, HttpServletRequest request){
        String filePath = "E:" +
                "/development/fileUp/";
        Random r=new Random();
        int rcode = r.nextInt(900000)+100000;
        String originalName = file.getOriginalFilename();
        long time = new Date().getTime();
        String filename = originalName.substring(originalName.lastIndexOf("\\")+1);
        //后缀名
        String fileExtName = filename.substring(filename.lastIndexOf(".")+1);
        filename = rcode+String.valueOf(time)+"."+fileExtName;
        //完整文件名（路径加文件名字）
        String lastFile = filePath + filename;
        try {
            this.uploadFile(file.getBytes(),filePath,filename);
            FileUp rb = new FileUp();
            rb.setCreateDate(new Date());
            rb.setFileName(filename);
            rb.setFilePath(filePath);
            rb.setFileSize(file.getBytes().length);
            rb.setUrl("file/fileAccess?filename="+filename);
            LOGGER.info("文件上传,文件名=="+filename);
            return ResponseResult.e(ResponseCode.OK,rb);
        } catch (Exception e) {
            throw RequestException.fail(-1,"文件上传失败",e);
        }
    }

    @RequestMapping(value = {"/fileAccess"},method = RequestMethod.GET)
    @ApiOperation(value = "文件获取")
    public ResponseResult<FileUp> fileAccess(@RequestParam("filename")String filename,HttpServletResponse response){
        String filePath = "/development/fileUp/";
        File file = new File(filePath+filename);
        if (file.exists()) {
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            try {
                //设置响应头，控制浏览器下载该文件
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
                //缓存文件流
                FileInputStream in = new FileInputStream("/development/fileUp/"+filename);
                OutputStream out = response.getOutputStream();
                byte[] buffer = new byte[1024 * 1024];
                int len = 0;
                //循环将输入流中的内容读取到缓冲区当中ss
                while ((len = in.read(buffer)) > 0) {
                    //输出缓冲区的内容到浏览器，实现文件下载
                    out.write(buffer, 0, len);
                }
                //关闭文件输入流
                in.close();
                //关闭输出流
                out.close();
            } catch (Exception e) {
                return ResponseResult.e(ResponseCode.FAIL, "文件下载出错");
            }

            return ResponseResult.e(ResponseCode.OK, "文件下载操作成功");
        }else {
            return ResponseResult.e(ResponseCode.FAIL, "文件路径或或文件名出错");
        }

    }

    public ResponseResult<CertificationDto> upLoadFile(){
        return null;
    }

    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }





}
